package edu.cqie.smartfarm.exception.handler;

import edu.cqie.smartfarm.constant.MessageConstant;
import edu.cqie.smartfarm.exception.annotation.GlobalException;
import edu.cqie.smartfarm.exception.exception.IGlobalException;
import edu.cqie.smartfarm.result.R;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@GlobalException(throwable = DataIntegrityViolationException.class)
public class DataIntegrityViolationExceptionHandler implements IGlobalException<ResponseEntity<R>, DataIntegrityViolationException> {
    @Override
    public ResponseEntity<R> exception(DataIntegrityViolationException throwable, HttpServletRequest request, HttpServletResponse response) {
        // 检查异常消息是否包含手机号重复的信息
        if (throwable.getMessage().contains("Duplicate entry") && throwable.getMessage().contains("user.phone")) {
            return new ResponseEntity<>(R.Failed(MessageConstant.PHONE_EXISTS), HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(R.Failed(MessageConstant.UNKNOWN_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
